package com.demo.mykotlin.activity

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.demo.mykotlin.bean.Fruit
import com.demo.mykotlin.adapter.FruitRecycleAdapter
import com.demo.mykotlin.R
import kotlinx.android.synthetic.main.activity_recycle.*

/**
 * 回收列表
 */
class RecycleActivity : BaseActivity() {
    private val fruitList = ArrayList<Fruit>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycle)

        initFruits()
        //设置列表布局样式
//        val layoutManager = LinearLayoutManager(this)
        //设置为横向滑动（默认纵向）
        // layoutManager.orientation=LinearLayoutManager.HORIZONTAL;

        //网格列表模式
        val layoutManager = GridLayoutManager(this, 3)

        //瀑布流模式
//        val layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)

        recyclerView.layoutManager = layoutManager
        val adapter = FruitRecycleAdapter(fruitList)
        recyclerView.adapter = adapter
    }

    private fun initFruits() {
        //重复执行n次函数
        repeat(20) {
            fruitList.add(
                Fruit(
                    getRandomLengthString("Apple"),
                    R.drawable.ic_launcher_foreground
                )
            )
            fruitList.add(
                Fruit(
                    getRandomLengthString("Banana"),
                    R.drawable.ic_launcher_background
                )
            )
        }
    }

    /**
     * 生成随机长度的字符串
     */
    private fun getRandomLengthString(str: String): String {
        //获得随机数值
        val n = (1..20).random()
        val builder = StringBuilder()
        //执行随机次追加字符串
        repeat(n) {
            builder.append(str)
        }
        return builder.toString()
    }

    /**
     * 跳转到本页
     */
    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, RecycleActivity::class.java)
            context.startActivity(intent)
        }
    }
}
